package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.FormatAdapter;
import flc.ast.bean.FormatBean;
import flc.ast.databinding.ActivityPlayFormatBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.video.VideoFormat;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.view.container.StkRecycleView;

public class PlayFormatActivity extends BaseAc<ActivityPlayFormatBinding> {

    public static String videoPath;
    private Dialog myFblDialog, myMlDialog, myZlDialog, myFormatDialog;
    private String selFormat = "", selFbl = "", selMl = "", selZl = "", newName = "", format = "avi";
    private EditText dialogRename;
    private TextView tvDialogFormatMp4, tvDialogFormatAvi, tvDialogFormatMkv, tvDialogFormat3gp, tvDialogFormatMov;
    private FormatAdapter fblAdapter, mlAdapter, zlAdapter;
    private List<FormatBean> fblList = new ArrayList<>();
    private List<FormatBean> mlList = new ArrayList<>();
    private List<FormatBean> zlList = new ArrayList<>();
    private int oldPosition1 = 0, oldPosition2 = 0, oldPosition3 = 0;
    private int selWidth, selHeight, ml;
    private long zl;

    @Override
    protected int onCreate() {
        return R.layout.activity_play_format;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);
        mDataBinding.ivPlayFormatBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.llFormatFormat.setOnClickListener(this);
        mDataBinding.llFormatFbl.setOnClickListener(this);
        mDataBinding.llFormatMl.setOnClickListener(this);
        mDataBinding.llFormatZl.setOnClickListener(this);
        mDataBinding.tvFormatStart.setOnClickListener(this);
        formatDialog();
        fblDialog();
        mlDialog();
        zlDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llFormatFormat:   // 选择格式
                myFormatDialog.show();
                break;
            case R.id.tvDialogFormatMp4:
                clearFormat();
                tvDialogFormatMp4.setBackgroundResource(R.drawable.shape_format_sel2);
                tvDialogFormatMp4.setTextColor(Color.parseColor("#FF202020"));
                format = "mp4";
                break;
            case R.id.tvDialogFormatMkv:
                clearFormat();
                tvDialogFormatMkv.setBackgroundResource(R.drawable.shape_format_sel2);
                tvDialogFormatMkv.setTextColor(Color.parseColor("#FF202020"));
                format = "mkv";
                break;
            case R.id.tvDialogFormatAvi:
                clearFormat();
                tvDialogFormatAvi.setBackgroundResource(R.drawable.shape_format_sel2);
                tvDialogFormatAvi.setTextColor(Color.parseColor("#FF202020"));
                format = "avi";
                break;
            case R.id.tvDialogFormat3gp:
                clearFormat();
                tvDialogFormat3gp.setBackgroundResource(R.drawable.shape_format_sel2);
                tvDialogFormat3gp.setTextColor(Color.parseColor("#FF202020"));
                format = "3gp";
                break;
            case R.id.tvDialogFormatMov:
                clearFormat();
                tvDialogFormatMov.setBackgroundResource(R.drawable.shape_format_sel2);
                tvDialogFormatMov.setTextColor(Color.parseColor("#FF202020"));
                format = "mov";
                break;
            case R.id.tvDialogFormatCancel:
                myFormatDialog.dismiss();
                break;
            case R.id.tvDialogFormatComp:
                selFormat = format;
                mDataBinding.tvFormatFormat.setText(selFormat);
                mDataBinding.tvFormatFormat.setTextColor(Color.parseColor("#FFFFFF"));
                myFormatDialog.dismiss();
                break;
            case R.id.llFormatFbl:  //分辨率
                myFblDialog.show();
                break;
            case R.id.tvDialogFblComp:
                selFbl = fblAdapter.getItem(oldPosition1).getStr();
                mDataBinding.tvFormatFbl.setText(selFbl);
                myFblDialog.dismiss();
                break;
            case R.id.tvDialogFblCancel:
                myFblDialog.dismiss();
                break;
            case R.id.llFormatMl: //码率
                myMlDialog.show();
                break;
            case R.id.tvDialogMlComp:
                selMl = mlAdapter.getItem(oldPosition2).getStr();
                mDataBinding.tvFormatMl.setText(selMl);
                myMlDialog.dismiss();
                break;
            case R.id.tvDialogMlCancel:
                myMlDialog.dismiss();
                break;
            case R.id.llFormatZl: //帧率
                myZlDialog.show();
                break;
            case R.id.tvDialogZlComp:
                selZl = zlAdapter.getItem(oldPosition3).getStr();
                mDataBinding.tvFormatZl.setText(selZl);
                myZlDialog.dismiss();
                break;
            case R.id.tvDialogZlCancel:
                myZlDialog.dismiss();
                break;
            case R.id.tvFormatStart:
                startConv();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == fblAdapter) {
            fblAdapter.getItem(oldPosition1).setSelect(false);
            fblAdapter.notifyItemChanged(oldPosition1);
            oldPosition1 = position;
            fblAdapter.getItem(position).setSelect(true);
            fblAdapter.notifyItemChanged(position);
        } else if (adapter == mlAdapter) {
            mlAdapter.getItem(oldPosition2).setSelect(false);
            mlAdapter.notifyItemChanged(oldPosition2);
            oldPosition2 = position;
            mlAdapter.getItem(position).setSelect(true);
            mlAdapter.notifyItemChanged(position);
        } else if (adapter == zlAdapter) {
            zlAdapter.getItem(oldPosition3).setSelect(false);
            zlAdapter.notifyItemChanged(oldPosition3);
            oldPosition3 = position;
            zlAdapter.getItem(position).setSelect(true);
            zlAdapter.notifyItemChanged(position);
        }
    }

    @Override
    protected void initData() {
        String fileName = FileUtils.getFileName(videoPath);
        mDataBinding.etFormatName.setText(fileName);

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(videoPath);

        int width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
        int height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));

        selFbl = width + "*" + height + "（原始分辨率）";
        selWidth = width;
        selHeight = height;
        mDataBinding.tvFormatFbl.setText(selFbl);

        File file = new File(videoPath);
        long size = 0;
        size = file.length();
        long size1 = size / 1024;


        String duration_s = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long duration = Long.valueOf(duration_s);
        long time = duration / 1000;

        ml = (int) (size1 * 8 / time);
        selMl = ml + "kb/s（原始码率）";
        mDataBinding.tvFormatMl.setText(selMl);

        //获取视频帧数
        String count_s = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT);
        long count = Long.valueOf(count_s);

        //计算帧率
        zl = duration / count; // 平均每帧的时间间隔，35ms
        selZl = zl + "帧/秒（原始帧率）";
        mDataBinding.tvFormatZl.setText(selZl);

    }

    //开始转换
    private void startConv() {
        if (TextUtils.isEmpty(selFormat)) {
            ToastUtils.showShort(R.string.please_sel_format);
        } else if (TextUtils.isEmpty(mDataBinding.etFormatName.getText().toString().trim())) {
            ToastUtils.showShort(getString(R.string.name_not_null));
        } else {
            mDataBinding.tvFormatStart.setEnabled(false);
            //整理参数
            int width = getWidth();
            int height = getHeight();
            int ml1 = getMl();
            String format = getFormat();
            comVideo(width, height, ml1, format);//修改参数其实就是压缩视频
        }
    }

    //开始转换(帧率无效，不管它)
    private void comVideo(int videoWidth, int videoHeight, int ml, String format) {

        EditorHolder.editor().videoCompress(videoPath, videoWidth, videoHeight, ml, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                mDataBinding.tvFormatStart.setEnabled(true);
                dismissDialog();
                ToastUtils.showShort(getString(R.string.conv_suc));
                saveVideo(outFilePath, format);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                mDataBinding.tvFormatStart.setEnabled(true);
                ToastUtils.showShort(R.string.conv_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.conv_ing) + progress + "%");
            }
        });
    }

    //保存视频
    private void saveVideo(String path, String format) {
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String filePath = FileUtil.generateFilePath(Content.myTemp, format);
                FileUtils.copy(path, filePath);
                emitter.onNext(filePath);
            }

            @Override
            public void accept(String savePath) {
                //重命名
                newName=mDataBinding.etFormatName.getText().toString().trim();
                FileUtils.rename(savePath, newName + format);
                String newPath = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + newName + format;
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, newPath);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        PlayLocalActivity.videoPath = newPath;
                        startActivity(PlayLocalActivity.class);
                    }
                }, 500);
            }
        });
    }

    private void formatDialog() {
        myFormatDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format, null);
        myFormatDialog.setContentView(inflate);
        myFormatDialog.setCancelable(true);
        Window dialogWindow = myFormatDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogFormatCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogFormatComp);
        tvDialogFormatMp4 = inflate.findViewById(R.id.tvDialogFormatMp4);
        tvDialogFormatAvi = inflate.findViewById(R.id.tvDialogFormatAvi);
        tvDialogFormatMkv = inflate.findViewById(R.id.tvDialogFormatMkv);
        tvDialogFormat3gp = inflate.findViewById(R.id.tvDialogFormat3gp);
        tvDialogFormatMov = inflate.findViewById(R.id.tvDialogFormatMov);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
        tvDialogFormatMp4.setOnClickListener(this);
        tvDialogFormatAvi.setOnClickListener(this);
        tvDialogFormatMkv.setOnClickListener(this);
        tvDialogFormat3gp.setOnClickListener(this);
        tvDialogFormatMov.setOnClickListener(this);
    }

    private void fblDialog() {
        myFblDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_fbl, null);
        myFblDialog.setContentView(inflate);
        myFblDialog.setCancelable(true);
        Window dialogWindow = myFblDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        TextView dialogComp = inflate.findViewById(R.id.tvDialogFblComp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogFblCancel);
        dialogComp.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
        fblAdapter = new FormatAdapter();
        recycleView.setAdapter(fblAdapter);
        fblList.add(new FormatBean("2k", true));
        fblList.add(new FormatBean("1080P（推荐）", false));
        fblList.add(new FormatBean("720P", false));
        fblList.add(new FormatBean("540P", false));
        fblList.add(new FormatBean("480P", false));
        fblAdapter.setList(fblList);
        fblAdapter.setOnItemClickListener(this);
    }

    private void mlDialog() {
        myMlDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_ml, null);
        myMlDialog.setContentView(inflate);
        myMlDialog.setCancelable(true);
        Window dialogWindow = myMlDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        TextView dialogComp = inflate.findViewById(R.id.tvDialogMlComp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogMlCancel);
        dialogComp.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
        mlAdapter = new FormatAdapter();
        recycleView.setAdapter(mlAdapter);
        mlList.add(new FormatBean("250kbps", true));
        mlList.add(new FormatBean("2000kbps", false));
        mlList.add(new FormatBean("5000kbps", false));
        mlList.add(new FormatBean("8000kbps", false));
        mlAdapter.setList(mlList);
        mlAdapter.setOnItemClickListener(this);

    }

    private void zlDialog() {
        myZlDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_zl, null);
        myZlDialog.setContentView(inflate);
        myZlDialog.setCancelable(true);
        Window dialogWindow = myZlDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        TextView dialogComp = inflate.findViewById(R.id.tvDialogZlComp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogZlCancel);
        dialogComp.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);

        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        zlAdapter = new FormatAdapter();
        recycleView.setAdapter(zlAdapter);
        zlList.add(new FormatBean("80fps", true));
        zlList.add(new FormatBean("50fps", false));
        zlList.add(new FormatBean("40fps", false));
        zlList.add(new FormatBean("30fps", false));
        zlList.add(new FormatBean("20fps", false));
        zlAdapter.setList(zlList);
        zlAdapter.setOnItemClickListener(this);

    }

    //根据选择的分辨率获取宽
    private int getWidth() {
        int width = selWidth;
        if (selFbl.equals("2k")) {
            width = 2560;
        } else if (selFbl.equals("1080P（推荐）")) {
            width = 1920;
        } else if (selFbl.equals("720P")) {
            width = 1280;
        } else if (selFbl.equals("540P")) {
            width = 960;
        } else if (selFbl.equals("480P")) {
            width = 640;
        }
        return width;
    }

    //根据选择的分辨率获取高
    private int getHeight() {
        int height = selHeight;
        if (selFbl.equals("2k")) {
            height = 1440;
        } else if (selFbl.equals("1080P（推荐）")) {
            height = 1080;
        } else if (selFbl.equals("720P")) {
            height = 720;
        } else if (selFbl.equals("540P")) {
            height = 540;
        } else if (selFbl.equals("480P")) {
            height = 480;
        }
        return height;
    }

    //根据选择的码率获取码率比例
    private int getMl() {
        int mBitrateScale = ml * 1024;
        if (selMl.equals("250kps")) {
            mBitrateScale = 250 * 1024;
        } else if (selMl.equals("2000kbps")) {
            mBitrateScale = 2000 * 1024;
        } else if (selMl.equals("5000kbps")) {
            mBitrateScale = 5000 * 1024;
        } else if (selMl.equals("8000kbps")) {
            mBitrateScale = 8000 * 1024;
        }
        return mBitrateScale;
    }

    //根据选择的格式获取格式后缀
    private String getFormat() {
        String format = VideoFormat.MP4.getSuffix();
        if (selFormat.equals("mp4")) {
            format = VideoFormat.MP4.getSuffix();
        } else if (selFormat.equals("avi")) {
            format = VideoFormat.AVI.getSuffix();
        } else if (selFormat.equals("mkv")) {
            format = VideoFormat.MKV.getSuffix();
        } else if (selFormat.equals("3gp")) {
            format = VideoFormat.THREE_GP.getSuffix();
        } else if (selFormat.equals("mov")) {
            format = VideoFormat.MOV.getSuffix();
        }
        return format;
    }

    @Override
    protected boolean isStatusBarTextDark() {
        return false;
    }

    private void clearFormat() {
        tvDialogFormatMp4.setBackgroundResource(R.drawable.shape_format_sel1);
        tvDialogFormatMp4.setTextColor(Color.parseColor("#FF8C8C8C"));
        tvDialogFormat3gp.setBackgroundResource(R.drawable.shape_format_sel1);
        tvDialogFormat3gp.setTextColor(Color.parseColor("#FF8C8C8C"));
        tvDialogFormatMkv.setBackgroundResource(R.drawable.shape_format_sel1);
        tvDialogFormatMkv.setTextColor(Color.parseColor("#FF8C8C8C"));
        tvDialogFormatAvi.setBackgroundResource(R.drawable.shape_format_sel1);
        tvDialogFormatAvi.setTextColor(Color.parseColor("#FF8C8C8C"));
        tvDialogFormatMov.setBackgroundResource(R.drawable.shape_format_sel1);
        tvDialogFormatMov.setTextColor(Color.parseColor("#FF8C8C8C"));
    }

}